// JavaScript Document

// --------------------------------------------------------------
// --------------------------------------------------------------
// Physics类只负责计算,不负责将计算结果更新到对象上

//PhysicsNode只负责记录每个object的物理信息, 用作物理模块的计算
//调用时object为Brick类型或者是Sprite类型
function PhysicsNode(pV, bR, vV, aV) 
{
    var _this = this;
    
    _this.position = pV;
    _this.box = bR;
    _this.velocity = vV;
    _this.acceleration = aV;
}

function Physics() 
{
	
	var _this = this;
	// 这个对象用于实现碰撞检测及物理计算
	// 只需要用牛顿第2定律
	//传参physicsNode为需更新位置的对象的物理信息节点
	_this.updateObject = function(physicsNode, delta)
	{
		// 更新物理位置信息
    	var positionX = physicsNode.velocity.x * delta + physicsNode.acceleration.x * delta  * delta / 2 + physicsNode.position.x;
     	var positionY = physicsNode.velocity.y * delta + physicsNode.acceleration.y * delta  * delta / 2 + physicsNode.position.y;
        physicsNode.position.x = positionX;
        physicsNode.position.y = positionY;
        //更新物理速度信息
        var velocityX = physicsNode.velocity.x + physicsNode.acceleration.x * delta;
        //var velocityX = physicsNode.velocity.x ;
        var velocityY = physicsNode.velocity.y + physicsNode.acceleration.y * delta;
        physicsNode.velocity.x = velocityX;
        physicsNode.velocity.y = velocityY;
        
	}
	
	_this.isInbox = function(minX, maxX, minY, maxY, X, Y)
	{
		if( minX < X && X < maxX && minY < Y && Y < maxY){
			return true;
		}
		return false;
	}
	
	_this.detectCollision = function (spriteNode, physicsNode) 
	{
		var minX = physicsNode.position.x + 10;
		var maxX = physicsNode.position.x + physicsNode.box.width - 10;
		var minY = physicsNode.position.y;
		var maxY = physicsNode.position.y + physicsNode.box.height;
		
		var leftX = spriteNode.position.x;
		var rightX = spriteNode.position.x + spriteNode.box.width;
		var topY = spriteNode.position.y;
		var bottomY = spriteNode.position.y + spriteNode.box.height;
		
		if( _this.isInbox(minX, maxX, minY, maxY, leftX, topY) ||
		    _this.isInbox(minX, maxX, minY, maxY, rightX, topY) ||
		    _this.isInbox(minX, maxX, minY, maxY, leftX, bottomY) ||
		    _this.isInbox(minX, maxX, minY, maxY, rightX, bottomY) 
		){
			return true;
		}

		 return false;
	}
	
	_this.smoothMove = function(physicsNode)
	{
	    physicsNode.acceleration.x = -physicsNode.acceleration.x;
	    
	}
	
	_this.ready = function ()
	{
		return true;
	}
	
}